<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\CartItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Services\CartService;
use App\Services\CartPriceService;
use App\Services\ProductService;
use App\Http\Requests\UpdateCartItemRequest;
use App\Http\Requests\StoreCartItemRequest;
use App\Jobs\UpdateCartPricesJob;
use App\Events\CartPriceChanged;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class CartController extends Controller
{
    protected ProductService $productService;

    public function __construct(ProductService $productService)
    {
        $this->productService = $productService;
    }
    /**
     * 显示购物车页面
     */
    public function index(Request $request, CartPriceService $priceService): Response
    {
        $cart = $this->getOrCreateCart($request);
        $cart->load(['items.product', 'items.variant']);
        
        // 更新价格并获取价格变动信息
        $priceChanges = $priceService->updateCartPrices($cart);
        $priceSummary = $priceService->getCartPriceSummary($cart);
        
        $cartItems = $cart->items->map(function ($item) {
            // 检查商品是否失效
            $isInvalid = false;
            $invalidReason = '';
            
            if (!$item->product) {
                $isInvalid = true;
                $invalidReason = '商品已删除';
            } elseif (!$item->product->is_active) {
                $isInvalid = true;
                $invalidReason = '商品已下架';
            } elseif ($item->variant_id) {
                if (!$item->variant) {
                    $isInvalid = true;
                    $invalidReason = '规格已删除';
                } elseif (!$item->variant->is_active) {
                    $isInvalid = true;
                    $invalidReason = '规格已下架';
                } elseif ($item->variant->stock_quantity <= 0) {
                    $isInvalid = true;
                    $invalidReason = '库存不足';
                }
            } else {
                if ($item->product->stock_quantity <= 0) {
                    $isInvalid = true;
                    $invalidReason = '库存不足';
                }
            }
            
            // 获取价格变动信息
            $priceInfo = $item->getPriceChangeInfo();
            
            return [
                'id' => $item->id,
                'product_id' => $item->product_id,
                'variant_id' => $item->variant_id,
                'name' => $item->product ? $item->product->name : '商品已删除',
                'description' => $item->product ? $item->product->description : '',
                'image' => $item->image ?: ($item->product->images[0] ?? '/images/placeholder.jpg'),
                'specs' => $item->specifications, // 返回原始数组
                'stock' => $item->variant ? $item->variant->stock_quantity : ($item->product ? $item->product->stock_quantity : 0),
                'price' => $item->price,
                'quantity' => $item->quantity,
                'subtotal' => $item->subtotal,
                'is_selected' => $item->is_selected, // 选中状态
                'is_invalid' => $isInvalid, // 是否失效
                'invalid_reason' => $invalidReason, // 失效原因
                'price_info' => $priceInfo, // 价格变动信息
            ];
        });
        
        return Inertia::render('Shop/Cart', [
            'cartItems' => $cartItems,
            'summary' => [
                'subtotal' => $cart->selected_subtotal, // 选中商品小计
                'shipping' => $cart->shipping_fee,
                'discount' => $cart->discount,
                'total' => $cart->total_amount,
                'itemCount' => $cart->total_quantity,
                'selectedItemCount' => $cart->selected_quantity, // 选中商品数量
            ],
            'priceSummary' => $priceSummary,
            'priceChangeNotification' => $priceService->generatePriceChangeNotification($priceSummary),
        ]);
    }

    /**
     * 加入购物车
     */
    public function add(StoreCartItemRequest $request)
    {

        $product = Product::findOrFail($request->product_id);
        $variant = $request->variant_id ? ProductVariant::findOrFail($request->variant_id) : null;

        // 检查库存
        $stock = $variant ? $variant->stock_quantity : $product->stock_quantity;
        if ($stock < $request->quantity) {
            return redirect()->back()->with('error', '库存不足');
        }

        DB::transaction(function () use ($request, $product, $variant) {
            $cart = $this->getOrCreateCart($request);
            
            // 查找是否已存在相同商品变体
            $existingItem = $cart->items()
                ->where('product_id', $product->id)
                ->where('variant_id', $variant?->id)
                ->first();

            if ($existingItem) {
                // 更新数量
                $newQuantity = $existingItem->quantity + $request->quantity;
                $stock = $variant ? $variant->stock_quantity : $product->stock_quantity;
                
                if ($newQuantity > $stock) {
                    $newQuantity = $stock;
                }
                
                $existingItem->update(['quantity' => $newQuantity]);
            } else {
                // 创建新商品项
                $price = $this->productService->getProductPrice($product, $variant);
                
                // 根据商品类型处理规格信息
                if ($product->product_type === 'single') {
                    // 单规格商品，不设置规格信息
                    $specifications = null;
                } else {
                    // 多规格商品，从变体获取规格信息
                    $specifications = $variant ? $this->productService->getVariantSpecifications($variant) : null;
                }
                
                $image = $this->productService->getProductImage($product, $variant);

                CartItem::create([
                    'cart_id' => $cart->id,
                    'product_id' => $product->id,
                    'variant_id' => $variant?->id,
                    'quantity' => $request->quantity,
                    'price' => $price,
                    'price_at_add' => $price,
                    'current_price' => $price,
                    'price_updated_at' => now(),
                    'specifications' => $specifications,
                    'image' => $image,
                ]);
            }
        });

        return redirect()->back();
    }

    /**
     * 更新购物车商品数量
     */
    public function update(UpdateCartItemRequest $request)
    {

        $item = CartItem::findOrFail($request->item_id);
        $stock = $item->variant ? $item->variant->stock_quantity : $item->product->stock_quantity;
        
        $quantity = min($request->quantity, $stock);
        $item->update(['quantity' => $quantity]);

        return redirect()->back();
    }

    /**
     * 移除购物车商品
     */
    public function remove(Request $request)
    {
        $request->validate([
            'item_id' => 'required|exists:cart_items,id',
        ]);

        CartItem::findOrFail($request->item_id)->delete();

        return redirect()->back();
    }

    /**
     * 批量删除购物车商品
     */
    public function batchRemove(Request $request)
    {
        $request->validate([
            'item_ids' => 'required|array',
            'item_ids.*' => 'exists:cart_items,id',
        ]);

        $cart = $this->getOrCreateCart($request);
        
        CartItem::whereIn('id', $request->item_ids)
            ->where('cart_id', $cart->id)
            ->delete();

        return redirect()->back()->with('success', '已删除选中的商品');
    }

    /**
     * 清空购物车
     */
    public function clear(Request $request)
    {
        $cart = $this->getOrCreateCart($request);
        $cart->items()->delete();

        return redirect()->back()->with('success', '购物车已清空');
    }

    /**
     * 批量移入收藏
     */
    public function batchMoveToFavorites(Request $request)
    {
        $request->validate([
            'item_ids' => 'required|array',
            'item_ids.*' => 'exists:cart_items,id',
        ]);

        // TODO: 实现收藏功能后完善此方法
        // 暂时只删除购物车项
        $cart = $this->getOrCreateCart($request);
        
        CartItem::whereIn('id', $request->item_ids)
            ->where('cart_id', $cart->id)
            ->delete();

        return redirect()->back()->with('success', '已移入收藏');
    }

    /**
     * 切换单个商品的选中状态
     */
    public function toggleSelect(Request $request)
    {
        $request->validate([
            'item_id' => 'required|exists:cart_items,id',
        ]);

        $cart = $this->getOrCreateCart($request);
        $item = CartItem::where('id', $request->item_id)
            ->where('cart_id', $cart->id)
            ->firstOrFail();

        $item->update(['is_selected' => !$item->is_selected]);

        return redirect()->back();
    }

    /**
     * 全选/取消全选（只对有效商品操作）
     */
    public function toggleSelectAll(Request $request)
    {
        $request->validate([
            'selected' => 'required|boolean',
        ]);

        $cart = $this->getOrCreateCart($request);
        $cart->load(['items.product', 'items.variant']);
        
        // 找出所有有效的商品ID
        $validItemIds = $cart->items->filter(function ($item) {
            if (!$item->product || !$item->product->is_active) {
                return false;
            }
            
            if ($item->variant_id) {
                if (!$item->variant || !$item->variant->is_active || $item->variant->stock_quantity <= 0) {
                    return false;
                }
            } else {
                if ($item->product->stock_quantity <= 0) {
                    return false;
                }
            }
            
            return true;
        })->pluck('id');
        
        // 只更新有效商品的选中状态
        $cart->items()->whereIn('id', $validItemIds)->update(['is_selected' => $request->selected]);

        return redirect()->back();
    }

    /**
     * 清理失效商品
     */
    public function clearInvalid(Request $request)
    {
        $cart = $this->getOrCreateCart($request);
        $cart->load(['items.product', 'items.variant']);
        
        // 找出所有失效的商品
        $invalidItems = $cart->items->filter(function ($item) {
            if (!$item->product || !$item->product->is_active) {
                return true;
            }
            
            if ($item->variant_id) {
                if (!$item->variant || !$item->variant->is_active || $item->variant->stock_quantity <= 0) {
                    return true;
                }
            } else {
                if ($item->product->stock_quantity <= 0) {
                    return true;
                }
            }
            
            return false;
        });
        
        // 删除失效商品
        $invalidItemIds = $invalidItems->pluck('id');
        $cart->items()->whereIn('id', $invalidItemIds)->delete();
        
        return redirect()->back()->with('success', "已清理 {$invalidItems->count()} 件失效商品");
    }

    /**
     * 获取或创建购物车
     */
    private function getOrCreateCart(Request $request): Cart
    {
        $cartService = new CartService();
        $userId = auth()->id();
        $sessionId = $request->session()->getId();

        // 如果是游客，尝试从session迁移购物车
        if (!$userId) {
            $cartService->migrateSessionCartToDatabase(null, $sessionId);
            return $cartService->getOrCreateCart(null, $sessionId);
        }

        // 用户登录后，优先使用用户ID查找购物车，确保与结算页面一致
        return $cartService->getOrCreateCart($userId, null);
    }

}